import axios from 'axios';
import qs from 'qs';
import { apiBasePath } from '@/api/config.ts';

axios.defaults.timeout = 3 * 1000;
axios.defaults.baseURL = apiBasePath;

interface ResponseData {
  code: number | string;
  data: any;
  err: string | undefined;
  message?: string;
}

axios.interceptors.response.use(
  (response) => {
    const data = response.data;
    const code = data.code;
    if (code === 403) {
      window.location.href = '/#/login';
      // Token过期了 删除Token
      localStorage.setItem('_mobile_site_token', '');
    }
    return response;
  },
  (error) => {
    console.error(error);
    return Promise.reject({
      code: 500,
      message: '服务器出错',
    });
  },
);

axios.interceptors.request.use(
  (config) => {
    if (localStorage.getItem('_mobile_site_token')) {
      config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('_mobile_site_token');
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

function get(url: any, params?: any): Promise<ResponseData> {
  return new Promise((resolve) => {
    axios
      .get(url, {
        params: params,
        paramsSerializer: (params) => {
          return qs.stringify(params, {
            indices: false,
            arrayFormat: 'repeat',
          });
        },
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
        },
      })
      .then((res) => {
        if (res) {
          const data = res.data;
          resolve({
            code: data.code,
            data: data.data || '',
            err: data.code === 200 ? void 0 : data.message,
          });
        }
      })
      .catch((e) => {
        console.error(e);
        resolve({
          code: 500,
          data: '',
          err: e.message,
        });
      });
  });
}

function post(url: string, data?: any, file?: any): Promise<ResponseData> {
  return new Promise((resolve) => {
    axios
      .post(url, data, {
        headers: {
          'Content-Type': file ? 'multipart/form-data' : 'application/json;charset=UTF-8',
        },
      })
      .then((res) => {
        const data = res.data;
        resolve({
          code: data.code,
          data: data.data || '',
          message: data.message || '',
          err: data.code === 200 ? void 0 : data.message,
        });
      })
      .catch((e) => {
        console.log(e);
        resolve({
          code: 500,
          data: '',
          err: e.message,
        });
      });
  });
}

export default {
  get,
  post,
};
